% POV_TREE   POV-Ray rendering of trees.
% (trees package)
%
% [name path, rpot] = pov_tree (intree, name, v, ipart, options)
% --------------------------------------------------------------
%
% writes POV-ray files using the anatomy-data contained in intree.
%
% Input
% -----
% - intree   ::integer:       index of tree in trees or structured tree or
%     cell-array of trees. Also: at any point instead of a full tree give a 
%     Nx4 matrix containing points [X Y Z D] rendered as spheres then.
% - name     ::string:        name of file including the extension ".pov"
%     spaces and other weird symbols not allowed!
%     {DEFAULT : open gui fileselect}
% - v        ::vector:        values to be colour-coded, cell array if for
%     more than one tree, same organization as intree.
% - ipart    ::index:   index to the subpart to be plotted, cell array if
%     for more than one tree, same organisation as intree.
%     {DEFAULT: all nodes}
%     NOTE! DOES NOT YET WORK WITH COLOUR_CODED VALUES IN V
% - options  ::string:  
%     '-b'   : blob, draws a skin around the cylinders
%     '-s'   : show, write an extra standard file to display the povray
%        object. The filename is the same but starts with 'sh'.
%        options are -s1.. -s6.
%        -s1 : black on white (no color mapping either)
%        -s2 : green fluorescence on black
%        -s3 : red coral and watersurface on z = 0 plane
%     '-w'   : waitbar
%     '-v'   : adopt viewpoint from currently active axis
%     '-c'   : brainbow colors (and '-cmax' sharp contrast brainbow)
%     '-minmax' : normalizes v values between min and max before
%         coloring, else: normalizes v values from zero to max before
%         coloring.
%     '->'   : send directly to windows (necessitates -s option)
%     {DEFAULT: '-b -w', because blob much much faster}
%
% Output
% ------
% - name   ::string:         name of output file;
%      if [] no file was selected -> no output 
% - path   ::sting:          path of the file,
%      complete string is therefore: [path name] 
% - rpot   ::vector:         binned vector used for the coloring
%
% Example
% -------
% pov_tree (sample_tree, [], [], '-w -b -s ->')
%
% See also plot_tree x3d_tree swc_tree
% Uses len_tree cyl_tree D
%
% edited by Calvin Schneider 11 June 2014 for speed improvement
%
% the TREES toolbox: edit, generate, visualise and analyse neuronal trees
% Copyright (C) 2009 - 2016  Hermann Cuntz

function [tname, path, rpot] = pov_tree (intree, tname, v, ipart, options)

% trees : contains the tree structures in the trees package
global       trees

if (nargin < 1) || isempty (intree)
    % {DEFAULT tree: last tree in trees cell array}
    intree   = length (trees); 
end;

% defining a name for the povray-tree
if (nargin < 2) || isempty (tname)
    [tname, path] = uiputfile ('.pov', 'export to POV-Ray', 'tree.pov');
    if tname  == 0,
        tname = [];
        return
    end
else
    path      = '';
end

% extract a sensible name from the filename string:
nstart       = unique ([0 strfind(tname, '/') strfind(tname, '\')]);
name         = tname  (nstart (end) + 1 : end - 4);
if nstart (end) > 0
    path     = [path tname(1 : nstart (end))];
    tname    (1 : nstart (end)) = '';
end
%  imaging file, if v not empty or '-c' or '-z' option:
name2        = [path name '.dat']; 
%  show file, with '-s' option:
name3        = [path 'sh' name '.pov'];

if (nargin < 3) || isempty (v)
    % {DEFAULT: no color mapping}
    v        = []; 
end

if (nargin < 4) || isempty (ipart)
    % {DEFAULT: all nodes}
    ipart    = []; 
end

if (nargin < 5) || isempty (options)
    % {DEFAULT: blobs (much faster) and waitbar}
    options  = '-b -w'; 
end

nextline     = [(char (13)), (char (10))];

% colour values in .dat file:
if ... 
        isempty (v) && ...
        isempty (strfind (options, '-c')) %&& ...
%         isempty (strfind (options, '-z'))
    iflag                      = 0;  % imaging is off, no colours.
else
    iflag                      = 1;  % imaging is on,  colours: v or rand
    % colormap, change if necessary:
    map                        = jet   (256);        
    % number of colormap entries:
    lenm                       = size  (map,    1);  
    povray                     = fopen (name2, 'w');     % .dat file
    if strfind                 (options, '-c') % brainbow (random colours)
        if iscell              (intree)        % many cells
            % concatenate all values between 0 and 1:
            rpot               = cell (1, length (intree));
            for counter        = 1 : length (intree)
                if isstruct    (intree{counter}) % tree
                    len        = len_tree (intree{counter});
                    N          = size     (intree{counter}.X, 1);
                    if ~isempty (ipart)
                        looper = ipart {counter};
                    else
                        looper = (1 : N)';
                    end
                    lenner     = sum      (len (looper) > 0.0001);
                else                           % spheres
                    N          = size     (intree{counter}, 1);
                    if ~isempty (ipart)
                        looper = ipart{counter};
                    else
                        looper = (1 : N)';
                    end
                    lenner     = length (looper);
                end
                R              = rand     (1, 3);
                if strfind     (options, '-cmax') % brainbow high contrast
                    R          = R -  min (R);
                    R          = R ./ max (R);
                end
                colorcode      = repmat   (R, lenner, 1);
                colorcode      = reshape  (colorcode', ...
                    numel (colorcode), 1);
                rpot {counter} = repmat   (counter / length (intree), ...
                    lenner, 1);
                if ~isempty    (colorcode)
                    fprintf    (povray, '%12.8f,\n', colorcode);
                end
            end
        else                                   % single cell
            rpot               = {};
            if isstruct (intree) || (numel (intree) == 1)
                len            = len_tree (intree);
                N              = size     (intree.X, 1);
                if ~isempty    (ipart)
                    looper     = ipart;
                else
                    looper     = (1 : N)';
                end
                lenner         = sum      (len (looper) > 0.0001);
            else
                N              = size     (intree, 1);
                if ~isempty    (ipart)
                    looper     = ipart;
                else
                    looper     = (1 : N)';
                end
                lenner         = length (looper);
            end
            R                  = rand     (1, 3);
            if strfind         (options, '-cmax') % brainbow high contrast
                R              = R -  min (R);
                R              = R ./ max (R);
            end
            colorcode          = repmat  (R, lenner, 1);            
            colorcode          = reshape  (colorcode', ...
                numel (colorcode), 1);
            rpot {1}           = zeros    (lenner, 1);
            if ~isempty        (colorcode)
                fprintf        (povray, '%12.8f,\n', colorcode);
            end
        end
    else
        if iscell              (intree)
            if isstruct        (intree {1})
                len            = len_tree (intree {1});
            else
                len            = ones (size (intree {1}, 1), 1);
            end
            vt                 = v {1};
            if size (vt, 2)    == 3
                rpot           = cell (1, length (intree));
                for counter    = 1 : length (intree)
                    if isstruct (intree{counter})
                        len    = len_tree (intree{counter});
                    else
                        len    = ones (size (intree{counter}, 1), 1);
                    end
                    vt         = v {counter};
                    if islogical (vt)
                        vt     = double (vt);
                    end
                    vt         = vt (len > 0.0001, :);
                    colorcode  = reshape (vt', length (vt) * 3, 1);
                    rpot{counter}  = vt;
                    fprintf    (povray, '%12.8f,\n', colorcode);
                end
            else
                if islogical   (vt)
                    vt         = double (vt);
                end
                vt             = vt (len > 0.0001);
                if isempty     (strfind (options, '-minmax'))
                    irange     = [(min (vt)) (max (vt))];
                else
                    irange     = [0 (max (vt))];
                end
                % first find v value range:
                for counter    = 2 : length (intree)
                    if isstruct (intree{counter})
                        len    = len_tree (intree{counter});
                    else
                        len    = ones (size (intree{counter}, 1), 1);
                    end
                    vt         = v {counter};
                    if islogical (vt)
                        vt     = double (vt);
                    end
                    vt         = vt (len > 0.0001);
                    if max (vt) > irange (2)
                        irange (2) = max (vt);
                    end
                    if strfind (options, '-minmax')
                        if min (vt) < irange (1)
                            irange (1) = min (vt);
                        end
                    end
                end
                % then create mapping for all trees:
                rpot           = cell (1, length (intree));
                for counter    = 1 : length (intree)
                    if isstruct (intree{counter})
                        len    = len_tree   (intree{counter});
                    else
                        len    = ones (size (intree{counter}, 1), 1);
                    end
                    vt         = v{counter};
                    if islogical (vt)
                        vt     = double (vt);
                    end
                    vt         = vt (len > 0.0001);
                    vt         = floor ((vt - irange (1)) ./ ...
                        ((irange (2) - irange (1)) ./ lenm));
                    vt (vt < 1)    = 1;
                    vt (vt > lenm) = lenm;
                    colorcode      = map (vt, :);
                    colorcode      = reshape (colorcode', ...
                        length (vt) * 3, 1);
                    rpot{counter}  = vt;
                    fprintf        (povray, '%12.8f,\n', colorcode);
                end
            end
        else
            if isstruct (intree) || (numel (intree) == 1)
                len            = len_tree (intree);
            else
                len            = ones (size (intree, 1), 1);
            end
            if size (v, 2)     == 3
                if islogical   (v)
                    v          = double (v);
                end
                v              = v (len > 0.0001, :);
                colorcode      = reshape (v', length (v) * 3, 1);
                rpot           = {};
                rpot {1}       = v;
                fprintf        (povray, '%12.8f,\n', colorcode);
            else
                if islogical   (v)
                    v          = double (v);
                end
                v              = v (len > 0.0001);
                if strfind     (options, '-minmax')
                    irange     = [(min (v)) (max (v))];
                else
                    irange     = [0 (max (v))];
                end
                v              = floor ((v - irange (1))./ ...
                    ((irange (2) - irange (1)) ./ lenm));
                v (v < 1)      = 1;
                v (v > lenm)   = lenm;
                colorcode      = map (v, :);
                colorcode      = reshape (colorcode', length (v) * 3, 1);
                rpot           = {};
                rpot {1}       = v;
                fprintf        (povray, '%12.8f,\n', colorcode);
            end
        end
    end
    fclose                     (povray); % close file
end

if iscell                      (intree)
    if strfind                 (options, '-s')
        % show option - extra file:
        X                      = cell (length (intree), 1); 
        Y                      = cell (length (intree), 1);
        for counter            = 1 :   length (intree)
            if isstruct         (intree{counter})
                X {counter}    = intree{counter}.X;
                Y {counter}    = intree{counter}.Y;
            else
                X {counter}    = intree{counter} (:, 1);
                Y {counter}    = intree{counter} (:, 2);
            end
        end
    end
    % file-pointer to the povray-file
    povray                     = fopen ([path tname], 'w');
    % Writing the cylinders into a povray variable called 'name'
    fwrite                     (povray, ...
        ['#declare ' name  ' = union {', nextline], 'char');
    if strfind                 (options, '-w')
        % waitbar option: initialization
        HW                     = waitbar (0, 'writing trees ...');
        set                    (HW, ...
            'Name',            '..PLEASE..WAIT..YEAH..');
    end
    for counterT                     = 1 : length (intree)
        if strfind             (options, '-w') % waitbar option: update
            if mod (counterT, 500)   == 0
                waitbar        (counterT ./ length (intree), HW);
            end
        end
        if isstruct             (intree{counterT}) % They are trees
            D                  = intree{counterT}.D;
            cyl                = cyl_tree (intree{counterT});
            len                = len_tree (intree{counterT});
            N                  = length (D);
            if ~isempty         (ipart)
                looper         = ipart {counterT}';
            else
                looper         = 1 : N;
            end
            if strfind         (options, '-b')
                % blob option:
                % skin around bodies, faster but sloppier
                if isempty     (ipart)
                    fwrite     (povray, ...
                        ['blob     { threshold .15  // cell obj #', ...
                        (num2str (counterT)), nextline], 'char');
                else
                    if ~isempty (find (len (looper) > 0.0001, 1))
                        fwrite  (povray, ...
                            ['blob     { threshold .15  // cell obj #', ...
                            (num2str (counterT)), nextline], 'char');
                    end
                end
            end
            for counter           = looper
                if len (counter)  > 0.0001
                    fwrite     (povray, ...
                        ['cylinder { <', ...
                        (sprintf ('%.4f', cyl (counter,   1))), ',',    ...
                        (sprintf ('%.4f', cyl (counter,   3))), ',',    ...
                        (sprintf ('%.4f', cyl (counter,   5))), '>, <', ...
                        (sprintf ('%.4f', cyl (counter,   2))), ',',    ...
                        (sprintf ('%.4f', cyl (counter,   4))), ',',    ...
                        (sprintf ('%.4f', cyl (counter,   6))), '>, ',  ...
                        (sprintf ('%.5f', D   (counter) / 2))], 'char');
                    if strfind (options, '-b')
                        % blob option:
                        % skin around bodies, faster but sloppier
                        fwrite (povray, ', 1', 'char');
                    end
                    if iflag
                        fwrite (povray, ...
                            [' texture {', ...
                            '#read (inning, R) ', ...
                            '#read (inning, G) ', ...
                            '#read (inning, B) ', ...
                            'pigment {color red R green G blue B}'], ...
                            'char');
                        if strfind                     (options, '-s1')
                             fwrite (povray, ...
                            ' finish  {ambient 1}', 'char');
                        end
                        fwrite     (povray, '}', 'char');
                    end
                    fwrite     (povray, ['}', nextline], 'char');
                end
            end
        else % They are spheres
            if strfind         (options, '-b')
                % blob option:
                % skin around bodies, faster but sloppier
                if isempty     (ipart)
                    fwrite     (povray, ...
                        ['blob     { threshold .15  // cell obj #', ...
                        (num2str (counterT)), nextline], 'char');
                else
                    if ~isempty (ipart {counterT})
                        fwrite  (povray, ...
                            ['blob     { threshold .15  // cell obj #', ...
                            (num2str (counterT)), nextline], 'char');
                    end
                end
            end
            N                  = size (intree{counterT}, 1);
            if ~isempty        (ipart)
                looper         = ipart{counterT}';
            else
                looper         = 1 : N;
            end            
            for counter        = looper
                fwrite         (povray, [ ...
                    'sphere { <', ...
                    (sprintf ('%.4f', intree{counterT} (counter, 1))), ...
                    ',',   ...
                    (sprintf ('%.4f', intree{counterT} (counter, 2))), ...
                    ',',   ...
                    (sprintf ('%.4f', intree{counterT} (counter, 3))), ...
                    '>, ', ...
                    (sprintf ('%.5f', intree{counterT} (counter, 4) / 2))], ...
                    'char');
                if strfind     (options, '-b') % CHANGED FINDSTR
                    fwrite     (povray, ', 1', 'char');
                end
                if iflag
                    fwrite (povray, ...
                        [' texture {', ...
                        '#read (inning, R) ', ...
                        '#read (inning, G) ', ...
                        '#read (inning, B) ', ...
                        'pigment {color red R green G blue B}'], ...
                        'char');
                    if strfind                     (options, '-s1')
                        fwrite (povray, ...
                            ' finish  {ambient 1}', 'char');
                    end
                    fwrite     (povray, '}', 'char');
                end
                fwrite         (povray, ['}', nextline], 'char');
            end
        end
        if strfind             (options, '-b')
            % blob option:
            % skin around bodies, faster but sloppier
            if  isempty        (ipart)
                fwrite         (povray, ['}', nextline], 'char');
                fwrite         (povray,       nextline,  'char');
            else
                if  ~isempty (find (len (looper) > 0.0001, 1))
                    fwrite     (povray, ['}', nextline], 'char');
                    fwrite     (povray,       nextline,  'char');
                end
            end
        end
    end
    if strfind                 (options, '-w') % waitbar option: close
        close                  (HW);
    end
    fwrite                     (povray, ['}', nextline], 'char');
    fclose                     (povray);
else
    X                          = {};
    Y                          = {};
    if ~isstruct               (intree),
        if (numel (intree) == 1)
            D                  = trees{intree}.D;
            if strfind         (options, '-s')
                % show option: extra file
                X{1}           = trees{intree}.X;
                Y{1}           = trees{intree}.Y;
            end
        else
            if strfind         (options, '-s')
                % show option: extra file
                X{1}           = intree (:, 1);
                Y{1}           = intree (:, 2);
            end
        end
    else
        D                      = intree.D;
        if strfind             (options, '-s')
            % show option: extra file
            X{1}               = intree.X;
            Y{1}               = intree.Y;
        end
    end
    % file-pointer to the povray-file
    povray                     = fopen ([path tname], 'w');
    % Writing the cylinders into a povray variable called 'name'
    fwrite                     (povray, ...
        ['#declare ' name ' = union {', nextline], 'char');
    if strfind                 (options, '-w')
        % waitbar option: initialization
        HW                     = waitbar (0, 'writing cylinders ...');
        set                    (HW, 'Name', '..PLEASE..WAIT..YEAH..');
    end
    if strfind (options, '-b')
        % blob option:
        % skin around bodies, faster but sloppier
        fwrite                 (povray, ...
            ['blob     { threshold .15', nextline], 'char');
    end
    if isstruct (intree) || (numel (intree) == 1)
        N                      = length (D);
        cyl                    = cyl_tree (intree);
        len                    = len_tree (intree);
        if ~isempty            (ipart)
            looper             = ipart';
        else
            looper             = 1 : N;
        end
        for counter            = looper
            if strfind         (options, '-w')
                % waitbar option: update
                if mod (counter, 500) == 0
                    waitbar    (counter / N, HW);
                end
            end
            if len (counter)   > 0.0001
                fwrite         (povray , ...
                    ['cylinder { <', ...
                    (sprintf ('%.4f', cyl (counter, 1))), ',',    ...
                    (sprintf ('%.4f', cyl (counter, 3))), ',',    ...
                    (sprintf ('%.4f', cyl (counter, 5))), '>, <', ...
                    (sprintf ('%.4f', cyl (counter, 2))), ',',    ...
                    (sprintf ('%.4f', cyl (counter, 4))), ',',    ...
                    (sprintf ('%.4f', cyl (counter, 6))), '>, ',  ...
                    (sprintf ('%.5f', D   (counter) / 2))], 'char');
                if strfind     (options, '-b')
                    % blob option:
                    % skin around bodies, faster but sloppier
                    fwrite     (povray, ', 1', 'char');
                end
                if iflag
                    fwrite (povray, ...
                        [' texture {', ...
                        '#read (inning, R) ', ...
                        '#read (inning, G) ', ...
                        '#read (inning, B) ', ...
                        'pigment {color red R green G blue B}'], ...
                        'char');
                    if strfind                     (options, '-s1')
                        fwrite (povray, ...
                            ' finish  {ambient 1}', 'char');
                    end
                    fwrite     (povray, '}', 'char');
                end
                fwrite         (povray, ['}', nextline], 'char');
            end
        end
    else
        N                      = size (intree, 1);
        if ~isempty            (ipart)
            looper             = ipart';
        else
            looper             = 1 : N;
        end
        for counter            = looper
            if strfind         (options, '-w') % CHANGED FINDSTR
                % waitbar option: update
                if mod         (counter, 500) == 0
                    waitbar    (counter ./ size (intree, 1), HW);
                end
            end
            fwrite             (povray, ...
                ['sphere { <', ...
                (sprintf ('%.4f', intree (counter, 1))), ',',   ...
                (sprintf ('%.4f', intree (counter, 2))), ',',   ...
                (sprintf ('%.4f', intree (counter, 3))), '>, ', ...
                (sprintf ('%.5f', intree (counter, 4) / 2))], 'char');
            if strfind         (options, '-b') % CHANGED FINDSTR
                % blob option:
                % skin around bodies, faster but sloppier
                fwrite         (povray, ', 1', 'char');
            end
            if iflag
                fwrite         (povray, ...
                    [' texture {', ...
                    '#read (inning, R) ', ...
                    '#read (inning, G) ', ...
                    '#read (inning, B) ', ...
                    'pigment {color red R green G blue B}'], ...
                    'char');
                if strfind     (options, '-s1')
                    fwrite     (povray, ...
                        ' finish  {ambient 1}', 'char');
                end
                fwrite         (povray, '}', 'char');
            end
            fwrite             (povray, ['}', nextline], 'char');
        end
    end
    if strfind                 (options, '-w')
        % waitbar option: close
        close                  (HW);
    end
    fwrite                     (povray, ['}', nextline], 'char');
    if strfind                 (options, '-b')
        % blob option:
        % skin around bodies, faster but sloppier
        fwrite                 (povray, ['}', nextline], 'char');
        fwrite                 (povray,       nextline,  'char');
    end
    fclose                     (povray);
end

if strfind                     (options, '-s')
    % show option: extra file
    a1                         = strfind (options, '-s');
    if length (options)        > a1 + 1
        typ                    = str2double (options (a1 + 2));
        if isnan (typ)
            typ                = 1;
        end
    else
        typ                    = 1;
    end
    povray                     = fopen (name3, 'w');
    X                          = cat (1, X{:});
    Y                          = cat (1, Y{:});
    dX                         = abs (max (X) - min (X));
    mX                         = min (X) + (max (X) - min (X)) ./ 2;
    mY                         = min (Y) + (max (Y) - min (Y)) ./ 2;
    % camera positions:
    if strfind                 (options, '-v')
        ax                     = get (gcf, 'CurrentAxes');
        if ~isempty            (ax)
            cpos               = get (ax, 'cameraposition');
            cangle             = get (ax, 'cameraviewangle') * 1.3;
            tpos               = get (ax, 'cameratarget');
            skyvec             = get (ax, 'CameraUpVector');
            uvec               = [1 0 0];
            cX                 = cpos (1);
            cY                 = cpos (2);
            cZ                 = cpos (3);
            tX                 = tpos (1);
            tY                 = tpos (2);
            tZ                 = tpos (3);
        else
             cX                = mX; 
             cY                = mY; 
             cZ                = -dX;
             tX                = mX; 
             tY                = mY; 
             tZ                = 0; 
             cangle            = 65;
        end
    else
       cX                      = mX;
       cY                      = mY;
       cZ                      = -dX;
       tX                      = mX;
       tY                      = mY;
       tZ                      = 0;
       cangle                  = 65;
    end
    if iflag
        % imaging is on
        fwrite                 (povray, ...
            ['#fopen inning        "' name '.dat" read', ...
            nextline], 'char');
    end
    fwrite                     (povray, ...
        ['#include             "' name '.pov"', ...
                nextline], 'char');
    fwrite                     (povray, ...
        ['#include             "colors.inc"', ...
                nextline], 'char');
    switch typ
        case 2 % fluorescence
            fwrite             (povray, ...
                ['', nextline], 'char');
            fwrite             (povray, ...
                ['background           {rgbt <0, 0, 0, 0.75>}', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['camera               {', nextline], 'char');
            if strfind         (options, '-v')
                fwrite         (povray, ...
                    ['  sky                <', ...
                    (num2str (skyvec (1))), ', ', ...
                    (num2str (skyvec (2))), ', ', ...
                    (num2str (skyvec (3))), '>',  ...
                    nextline], 'char');
                fwrite         (povray, ...
                    ['  up                 <', ...
                    (num2str (uvec (1))), ', ' , ...
                    (num2str (uvec (2))), ', ' , ...
                    (num2str (uvec (3))), '>' , ...
                    nextline], 'char');
            end
            fwrite             (povray, ...
                ['  right              x * image_width / image_height', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  location           <', ...
                (num2str (cX)), ', ', ...
                (num2str (cY)), ', ', ...
                (num2str (cZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  look_at            <', ...
                (num2str (tX)), ', ', ...
                (num2str (tY)), ', ', ...
                (num2str (tZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  /*', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  // uncomment for focal blur', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['  focal_point        <', ...
                (num2str(tX)), ', ', ...
                (num2str(tY)), ', ', ...
                (num2str(tZ)), ' - 150>', ...
                nextline], 'char');

            fwrite             (povray, ...
                ['  aperture           50', ... 
                ' // increase for more focal blur', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  blur_samples       150 */', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  angle              ', ...
                (num2str (cangle)), ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', nextline], 'char');
            fwrite             (povray, ...
                ['',  nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <', ...
                (num2str (cX)) ', ', ...
                (num2str (cY)) ', ', ...
                (num2str (cZ)) '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  White', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['  fade_distance      500', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <0, 0, 0>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  color rgb          <1, 1, 0>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  looks_like         {' name, ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    texture          {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      pigment        {', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['        rgbft        <0.2, 1.0, 0.2, 0.15, 0.5>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      finish         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['        ambient      0.8', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['        diffuse      0.6', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['        reflection   0.28', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['        ior          3', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['        specular     1', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['        roughness    0.001', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['      }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');
            fclose             (povray);
        case 1 % no reflection on white background
            fwrite             (povray, ...
                ['', nextline], 'char');
            fwrite             (povray, ...
                ['background           {rgbt <1, 1, 1, 0>}', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['camera               {', nextline], 'char');
            if strfind         (options, '-v')
                fwrite         (povray, ...
                    ['  sky                <', ...
                    (num2str (skyvec (1))), ', ', ...
                    (num2str (skyvec (2))), ', ', ...
                    (num2str (skyvec (3))), '>',  ...
                    nextline], 'char');
                fwrite         (povray, ...
                    ['  up                 <', ...
                    (num2str (uvec (1))), ', ' , ...
                    (num2str (uvec (2))), ', ' , ...
                    (num2str (uvec (3))), '>' , ...
                    nextline], 'char');
            end
            fwrite             (povray, ...
                ['  right              x * image_width / image_height', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  location           <', ...
                (num2str (cX)), ', ', ...
                (num2str (cY)), ', ', ...
                (num2str (cZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  look_at            <', ...
                (num2str (tX)), ', ', ...
                (num2str (tY)), ', ', ...
                (num2str (tZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  angle              ', ...
                (num2str (cangle)), ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', nextline], 'char');
            fwrite             (povray, ...
                ['',  nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <', ...
                (num2str (cX)) ', ', ...
                (num2str (cY)) ', ', ...
                (num2str (cZ)) '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <0, 0, 0>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  looks_like         {', name, ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    texture          {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      pigment {rgb <0, 0, 0>}', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      finish  {ambient 1}', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['    }', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['  }', ...
                nextline], 'char');             
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');
            fclose             (povray);
        case 3 % red coral and watersurface on z = 0 plane
            fwrite             (povray, ...
                ['', nextline], 'char');
            fwrite             (povray, ...
                ['background           {rgbt <0.7, 0.7, 0.7, 0.75>}', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['camera               {', nextline], 'char');
            if strfind         (options, '-v')
                fwrite         (povray, ...
                    ['  sky                <', ...
                    (num2str   (skyvec (1))), ', ', ...
                    (num2str   (skyvec (2))), ', ', ...
                    (num2str   (skyvec (3))), '>',  ...
                    nextline], 'char');
                fwrite         (povray, ...
                    ['  up                 <', ...
                    (num2str   (uvec (1))), ', ' , ...
                    (num2str   (uvec (2))), ', ' , ...
                    (num2str   (uvec (3))), '>' , ...
                    nextline], 'char');
            end
            fwrite             (povray, ...
                ['  right              x * image_width / image_height', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  location           <', ...
                (num2str (cX)), ', ', ...
                (num2str (cY)), ', ', ...
                (num2str (cZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  look_at            <', ...
                (num2str (tX)), ', ', ...
                (num2str (tY)), ', ', ...
                (num2str (tZ)), '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  /*', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  // uncomment for focal blur', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['  focal_point        <', ...
                (num2str (tX)), ', ', ...
                (num2str (tY)), ', ', ...
                (num2str (tZ)), ' - 150>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  aperture           50', ...
                '// increase for more focal blur', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  blur_samples       150 */', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  angle              ', ...
                (num2str (cangle)), ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', nextline], 'char');
            fwrite             (povray, ...
                ['',  nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <', ...
                (num2str (cX)) ', ', ...
                (num2str (cY)) ', ', ...
                (num2str (cZ)) '>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  White', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['  fade_distance      500', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['plane                {    //plane of water at z=0', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  z,                 0', ...
                nextline], 'char');
            
            fwrite             (povray, ...
                ['  pigment            {', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['    rgbt             <1.0, 1.0, 0.5, 0.75>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  finish             {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    ambient          0.15', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['    diffuse          0.55', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['    reflection       0.2', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['    brilliance       6.0', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['  }', ...
            nextline], 'char');             
            fwrite             (povray, ...
                ['  normal             {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    bumps            0.5', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['    scale            20', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['    turbulence       1', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['  }', ...
            nextline], 'char');  
            fwrite             (povray, ...
                ['} ', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['light_source         {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  <0, 0, 0>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  color rgb          <1, 1, 0>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['  looks_like         {' name, ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    hollow interior  {media {emission 0}}', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    pigment          {', ...
                nextline], 'char');            
            fwrite             (povray, ...
                ['      rgbt           <0.5, 0, 0, 0.2>', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['    normal           {', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['      wrinkles       1.25', ...
                nextline], 'char');              
            fwrite             (povray, ...
                ['      scale          0.35', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['    }', ...
                nextline], 'char');  
            fwrite             (povray, ...
                ['  }', ...
                nextline], 'char');
            fwrite             (povray, ...
                ['}', ...
                nextline], 'char');
            fclose             (povray);
    end
    if  strfind                (options, '->')
        if  ispc
            % this even calls the file directly (only windows)
            winopen            (name3);
        end
    end
end



